<template>
  <div>
    <el-form ref="searchFrom" :model="queryParams" label-width="80" :inline="true">
      <el-form-item label="导航名称" prop="title">
        <el-input v-model="queryParams.name" style="width:200px" :clearable="true" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="getList">查询</el-button>
        <el-button icon="Refresh" @click="resetParams"> 重置 </el-button>
      </el-form-item>
    </el-form>
    <div>
      <el-button type="primary" icon="Plus" class="min-w-24" @click="handleAdd">新增</el-button>
    </div>
    <div class="mt-4 overflow-y-auto" style="max-height: 400px">
      <el-table v-loading="loading" :data="navList" border stripe>
        <el-table-column label="#" align="center" width="80">
          <template #default="scope">
            {{ scope.$index + basePage + 1 }}
          </template>
        </el-table-column>
        <el-table-column label="导航名称" align="center" prop="name" />
        <el-table-column label="排序" align="center" prop="sort" width="80" />
        <el-table-column label="坐标" align="center" prop="coordinate" />
        <el-table-column label="前图" align="center" prop="firstImage" show-overflow-tooltip />
        <el-table-column label="后图" align="center" prop="secondImage" show-overflow-tooltip>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" />
        <el-table-column label="修改时间" align="center" prop="modifyTime" />
        <!-- <el-table-column label="备注" align="center" prop="description" /> -->
        <el-table-column label="操作" align="center">
          <template #default="scope">
            <el-button link type="primary" size="small" @click="handleUpdate(scope.row)">
              编辑
            </el-button>
            <el-button link type="primary" size="small" @click="handleDelete(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageIndex"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <el-drawer v-model="dialogShow" :title="title" size="800" @closed="handleClosed">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80">
        <el-form-item label="导航名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入导航名称" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="form.sort" :precision="0" placeholder="1" />
        </el-form-item>
        <el-form-item label="上传图片" prop="fileList1">
          <div class="flex flex-col gap-2">
            <el-upload ref="frontRef" v-model:file-list="frontImg" :action="uploadFileUrl" :on-success="handleUpload1"
              :on-remove="handleRemove1" :show-file-list="false" list-type="picture">
              <el-button type="primary" class="min-w-24">上传前图</el-button>
              <el-button type="primary" class="min-w-24" @click="handlePreivew1">
                预览
              </el-button>
            </el-upload>
            <div v-if="form.firstImage" class="size-24 relative rounded-lg overflow-hidden border">
              <el-button link icon="CircleCloseFilled" @click="handleClear1" class="absolute right-1 top-1" />
              <img :src="`${baseUrl}${form.firstImage}`" class="h-full object-cover" />
            </div>
            <div v-else>暂无上传</div>
          </div>
        </el-form-item>
        <el-form-item label="" prop="fileList2">
          <div class="flex flex-col gap-2">
            <el-upload ref="backRef" v-model:file-list="backImg" :action="uploadFileUrl" :on-success="handleUpload2"
              :on-remove="handleRemove2" :show-file-list="false" list-type="picture">
              <el-button type="primary" class="min-w-24">上传后图</el-button>
              <el-button type="primary" class="min-w-24" @click="handlePreivew2">
                预览
              </el-button>
            </el-upload>
            <div v-if="form.secondImage" class="size-24 relative rounded-lg overflow-hidden border">
              <el-button link icon="CircleCloseFilled" @click="handleClear2" class="absolute right-1 top-1" />
              <img :src="`${baseUrl}${form.secondImage}`" class="h-full object-cover" />
            </div>
            <div v-else>暂无上传</div>
          </div>
        </el-form-item>
        <div class="flex gap-2">
          <el-form-item label="坐标 X" prop="x">
            <el-input-number v-model="form.x" controls-position="right" />
          </el-form-item>
          <el-form-item label="Y" prop="y" label-width="50">
            <el-input-number v-model="form.y" controls-position="right" />
          </el-form-item>
        </div>
        <el-form-item label="创建时间" prop="createTime">
          <el-input v-model="form.createTime" disabled placeholder="创建时间" />
        </el-form-item>
        <el-form-item label="修改时间" prop="modifyTime">
          <el-input v-model="form.modifyTime" disabled placeholder="修改时间" />
        </el-form-item>
        <el-form-item label="备注" prop="description">
          <el-input v-model="form.description" type="textarea" :rows="3" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup>
import {
  ref,
  reactive,
  toRefs,
  nextTick,
  computed,
  onMounted,
  getCurrentInstance,
} from "vue";
import {
  listShadowMenu,
  getShadowMenu,
  addShadowMenu,
  updateShadowMenu,
  deleteShadowMenu,
} from "@/api/shadow.js";
import { genFileId } from "element-plus";

const { proxy } = getCurrentInstance();
const uploadFileUrl = ref("/api/admin/Tools/upload");

const navList = ref([]);
const frontImg = ref([]);
const backImg = ref([]);
const total = ref(0);
const loading = ref(false);
const dialogShow = ref(false);
const title = ref(null);
const data = reactive({
  form: {},
  rules: {
    name: [{ required: true, message: "请输入导航名称", trigger: "blur" }],
    x: [{ required: true, message: "请输入坐标x值", trigger: "blur" }],
    y: [{ required: true, message: "请输入坐标y值", trigger: "blur" }],
  },
  queryParams: {
    pageIndex: 1,
    pageSize: 10,
    name: ''
  },
});
const { form, rules, queryParams } = toRefs(data);

const basePage = computed(() => {
  const { pageIndex, pageSize } = queryParams.value;
  return (pageIndex - 1) * pageSize;
});

function getList() {
  loading.value = true;
  listShadowMenu(queryParams.value).then((res) => {
    navList.value = res.data.dataSource;
    loading.value = false;
    total.value = res.data.recordsCount;
  });
}

function handleUpload1() {
  form.value.firstImage = frontImg.value[0].response;
  proxy.$refs["frontRef"].clearFiles();
}

function handlePreivew1() {
  const url = form.value.firstImage;
  if (url) window.open(baseUrl + url, "_blank");
}

function handleClear1() {
  proxy.$refs["frontRef"].clearFiles();
  form.value.firstImage = null;
}

function handleRemove1() {
  form.value.firstImage = null;
}

function handleUpload2() {
  form.value.secondImage = backImg.value[0].response;
  proxy.$refs["backRef"].clearFiles();
}

function handlePreivew2() {
  const url = form.value.secondImage;
  if (url) window.open(baseUrl + url, "_blank");
}

function handleClear2() {
  proxy.$refs["backRef"].clearFiles();
  form.value.secondImage = null;
}

function handleRemove2() {
  form.value.secondImage = null;
}

function handleAdd() {
  form.value = { sort: 1, x: 0, y: 0 };
  frontImg.value = [];
  backImg.value = [];
  dialogShow.value = true;
  title.value = "新增";
}

function handleUpdate(row) {
  getShadowMenu({ id: row.id }).then((res) => {
    form.value = res.data;
    const coordinate = res.data.coordinate?.split(",");
    if (coordinate && coordinate.length === 2) {
      form.value.x = Number(coordinate[0]);
      form.value.y = Number(coordinate[1]);
    } else {
      form.value.x = 0;
      form.value.y = 0;
    }
    dialogShow.value = true;
    title.value = "编辑";
  });
}

function handleDelete(row) {
  proxy.$modal
    .confirm('确认删除"' + row.name + '"?')
    .then(() => {
      return deleteShadowMenu({ id: row.id });
    })
    .then((res) => {
      proxy.$modal.msgSuccess("删除成功");
      getList();
    });
}

function submitForm() {
  proxy.$refs["formRef"].validate((valid) => {
    if (valid) {
      form.value.coordinate = `${form.value.x},${form.value.y}`;
      if (form.value.id != undefined) {
        updateShadowMenu(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          dialogShow.value = false;
          getList();
        });
      } else {
        addShadowMenu(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          dialogShow.value = false;
          getList();
        });
      }
    }
  });
}

function cancel() {
  dialogShow.value = false;
  handleClosed();
}

function handleClosed() {
  frontImg.value = [];
  backImg.value = [];
}

//重置
function resetParams() {
  queryParams.value.name = '';
}

//页面加载
onMounted(() => {
  getList();
})

</script>
